function [likel,ssvec,flag_ok,lht] = lmj_likel(parest, parvec, parposest, funcmod, Y, trainvec, solveopt, addsol) 
% =========================================================================
% LMJ_LIKEL.m
% [likel, ssvec,flag_ok,lht] = lmj_likel(estpr, fullp, indp, indmat, modstr, Y, trainvec,
% options, addsol) 
% m-file to compute the likelihood of LMJ class models.
% 
% Since the structure of the LMJEXOG model is such that
% [GG, RR, CONS, eu, SDX, ZZ, initss, ssvec, flag, ssnames]=feval(funcmod,param,options,addsol);
% two additional input OPTIONS and ADDSOL are needed. 
% 
% For: Alejandro Justiniano's LMJ Project (Spring 2010)
% RA: Xi Luo
% File Created on 04/07/2010
% 
% Modified June 29 2010 for compatibility with other functions called in 
% LMJ_LIKELCENTRAL 
% 1) Default value for problems with solution must be -1e40 
% 2) FLAG_OK == 0 if there are any problems with the solution 
% 3) Added Normalizing constant to the likelihood 
% =========================================================================
likel=-1e40; flag_ok=0; 
parvec(parposest)=parest; 
[G1, impact, C,eu,SDX,ZZ,~,ssvec]=feval(funcmod,parvec,solveopt,addsol);
% A. Non-existence 
if isequal(eu,[1;1])==0;
    return;
end
[T,nn]=size(Y);
if any(C~=0)==1;Y=Y-repmat((ZZ*C)',[T 1]);end;
Y=Y';MM=impact*(SDX');
try
    % B. Problems with initialization
    pshat=feval(@lyapunov_symm,G1,MM*(MM')); 
    if ~isempty(find(isnan(pshat))~=0)
        disp('PSHAT contains Nan entries') 
        return
    end 
    if ~isempty(find(isinf(abs(pshat)))~=0)
        disp('PSHAT contains Infinite entries')
        return
    end
catch
    disp('Warning! Problems with initialization in GENSYSPOST_VEC');
    save lmj_likel_errormat; 
    return
end
shat=zeros(size(G1,1),1);lht=zeros(T,1);
try
    % C. Problems with filter 
    for ii=1:T;
        [shat,pshat,lht(ii)]=feval(@kf,Y(:,ii),ZZ,shat,pshat,G1,MM);
    end
catch
    size(G1) 
    size(MM) 
    max(eig(GG)) 
    disp('Warning! Problems with Kalman filter in GENSYSPOS');
    save lmj_likel_errormat;
    error('Code crashed'); 
    return
end
lht=lht(trainvec(1):trainvec(2)); 
likel=-0.5*length(lht)*nn*log(2*pi)+sum(lht);
flag_ok=1; 